using System.Text;
using AdmissionQA.Application.Common;
using AdmissionQA.Application.Dtos.QAHistory;
using AdmissionQA.Application.ServiceInterfaces;
using Microsoft.AspNetCore.Mvc;

namespace AdmissionQA.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class DeepSeekQAController(
    IServiceProvider serviceProvider,
    IDeepSeekService deepSeekService,
    IQAHistoryServices qaHistoryServices) : ControllerBase
{
    private readonly IServiceProvider _serviceProvider = serviceProvider;
    private readonly IDeepSeekService _deepSeekService = deepSeekService;
    private readonly IQAHistoryServices _qaHistoryServices = qaHistoryServices;

    /// <summary>
    /// DeepSeek流式智能问答
    /// </summary>
    /// <param name="query">用户问题</param>
    /// <param name="topK">每个模块返回的结果数量，默认3个</param>
    /// <returns>流式AI回答</returns>
    [HttpGet("stream-qa")]
    public async Task<IActionResult> StreamQA([FromQuery] string query, [FromQuery] int topK = 3, CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrWhiteSpace(query))
        {
            return BadRequest("问题不能为空");
        }

        try
        {
            // 收集相关上下文信息
            var contextBuilder = new StringBuilder();
            var moduleResults = new Dictionary<string, object>();

            // 顺序查询各个模块
            using (var scope1 = _serviceProvider.CreateScope())
            {
                var issueServices = scope1.ServiceProvider.GetRequiredService<IIssueServices>();
                var issueResult = await issueServices.SearchIssuesByEmbeddingAsync(query, topK);
                if (issueResult.Data?.Any() == true)
                {
                    moduleResults["问答库"] = issueResult.Data;
                    contextBuilder.AppendLine("问答库信息：");
                    foreach (var item in issueResult.Data)
                    {
                        contextBuilder.AppendLine($"问题：{item.Question}");
                        contextBuilder.AppendLine($"答案：{item.Answer}");
                    }
                }
            }

            using (var scope2 = _serviceProvider.CreateScope())
            {
                var admissionPolicyServices = scope2.ServiceProvider.GetRequiredService<IAdmissionPolicyServices>();
                var policyResult = await admissionPolicyServices.SearchAdmissionPoliciesByEmbeddingAsync(query, topK);
                if (policyResult.Data?.Any() == true)
                {
                    moduleResults["招生政策"] = policyResult.Data;
                    contextBuilder.AppendLine("招生政策信息：");
                    foreach (var item in policyResult.Data)
                    {
                        contextBuilder.AppendLine($"政策名称：{item.AdmissionPolicyName}");
                        contextBuilder.AppendLine($"政策内容：{item.AdmissionPolicyContent}");
                    }
                }
            }

            using (var scope3 = _serviceProvider.CreateScope())
            {
                var majorInfoServices = scope3.ServiceProvider.GetRequiredService<IMajorInfoServices>();
                var majorResult = await majorInfoServices.SearchMajorInfosByEmbeddingAsync(query, topK);
                if (majorResult.Data?.Any() == true)
                {
                    moduleResults["专业信息"] = majorResult.Data;
                    contextBuilder.AppendLine("专业信息：");
                    foreach (var item in majorResult.Data)
                    {
                        contextBuilder.AppendLine($"专业名称：{item.MajorName}");
                        contextBuilder.AppendLine($"课程：{string.Join(", ", item.Courses)}");
                        contextBuilder.AppendLine($"就业前景：{item.CareerProspects}");
                    }
                }
            }

            using (var scope4 = _serviceProvider.CreateScope())
            {
                var scholarshipInfoServices = scope4.ServiceProvider.GetRequiredService<IScholarshipInfoServices>();
                var scholarshipResult = await scholarshipInfoServices.SearchScholarshipInfosByEmbeddingAsync(query, topK);
                if (scholarshipResult.Data?.Any() == true)
                {
                    moduleResults["奖学金信息"] = scholarshipResult.Data;
                    contextBuilder.AppendLine("奖学金信息：");
                    foreach (var item in scholarshipResult.Data)
                    {
                        contextBuilder.AppendLine($"奖学金名称：{item.ScholarshipName}");
                        contextBuilder.AppendLine($"金额：{item.Amount}");
                        contextBuilder.AppendLine($"申请条件：{item.Requirements}");
                    }
                }
            }

            using (var scope5 = _serviceProvider.CreateScope())
            {
                var campusLifeServices = scope5.ServiceProvider.GetRequiredService<ICampusLifeServices>();
                var campusResult = await campusLifeServices.SearchCampusLifesByEmbeddingAsync(query, topK);
                if (campusResult.Data?.Any() == true)
                {
                    moduleResults["校园生活"] = campusResult.Data;
                    contextBuilder.AppendLine("校园生活信息：");
                    foreach (var item in campusResult.Data)
                    {
                        contextBuilder.AppendLine($"类别：{item.Category}");
                        contextBuilder.AppendLine($"描述：{item.Description}");
                    }
                }
            }

            using (var scope6 = _serviceProvider.CreateScope())
            {
                var tuitionFeeServices = scope6.ServiceProvider.GetRequiredService<ITuitionFeeServices>();
                var tuitionResult = await tuitionFeeServices.SearchTuitionFeesByEmbeddingAsync(query, topK);
                if (tuitionResult.Data?.Any() == true)
                {
                    moduleResults["学费信息"] = tuitionResult.Data;
                    contextBuilder.AppendLine("学费信息：");
                    foreach (var item in tuitionResult.Data)
                    {
                        contextBuilder.AppendLine($"学费：{item.TuitionAmount}");
                        contextBuilder.AppendLine($"住宿费：{item.AccommodationFee}");
                        contextBuilder.AppendLine($"描述：{item.Description}");
                    }
                }
            }

            var context = contextBuilder.ToString();
            if (string.IsNullOrEmpty(context))
            {
                context = "暂无相关信息";
            }

            // 记录问答历史
            var qaHistory = new QAHistoryDto
            {
                Query = query,
                Answer = $"查询了{moduleResults.Count}个模块，使用DeepSeek AI回答",
                QueryType = "DeepSeek流式问答",
                Confidence = moduleResults.Count > 0 ? "高" : "低",
                UserIP = HttpContext.Connection.RemoteIpAddress?.ToString(),
                UserAgent = HttpContext.Request.Headers["User-Agent"].ToString()
            };

            await _qaHistoryServices.CreateQAHistoryAsync(qaHistory);

            // 返回流式响应
            Response.Headers["Content-Type"] = "text/plain; charset=utf-8";
            Response.Headers["Cache-Control"] = "no-cache";
            Response.Headers["Connection"] = "keep-alive";

            await foreach (var chunk in _deepSeekService.StreamChatAsync(query, context, cancellationToken))
            {
                await Response.WriteAsync(chunk, cancellationToken);
                await Response.Body.FlushAsync(cancellationToken);
            }

            return new EmptyResult();
        }
        catch (Exception ex)
        {
            return StatusCode(500, new
            {
                Query = query,
                Error = "DeepSeek AI服务暂时不可用，请稍后重试",
                Details = ex.Message,
                Source = "DeepSeek流式问答系统"
            });
        }
    }

    /// <summary>
    /// DeepSeek非流式智能问答
    /// </summary>
    /// <param name="query">用户问题</param>
    /// <param name="topK">每个模块返回的结果数量，默认3个</param>
    /// <returns>AI回答</returns>
    [HttpGet("chat-qa")]
    public async Task<IActionResult> ChatQA([FromQuery] string query, [FromQuery] int topK = 3, CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrWhiteSpace(query))
        {
            return BadRequest("问题不能为空");
        }

        try
        {
            // 收集相关上下文信息
            var contextBuilder = new StringBuilder();
            var moduleResults = new Dictionary<string, object>();

            // 顺序查询各个模块
            using (var scope1 = _serviceProvider.CreateScope())
            {
                var issueServices = scope1.ServiceProvider.GetRequiredService<IIssueServices>();
                var issueResult = await issueServices.SearchIssuesByEmbeddingAsync(query, topK);
                if (issueResult.Data?.Any() == true)
                {
                    moduleResults["问答库"] = issueResult.Data;
                    contextBuilder.AppendLine("问答库信息：");
                    foreach (var item in issueResult.Data)
                    {
                        contextBuilder.AppendLine($"问题：{item.Question}");
                        contextBuilder.AppendLine($"答案：{item.Answer}");
                    }
                }
            }

            using (var scope2 = _serviceProvider.CreateScope())
            {
                var admissionPolicyServices = scope2.ServiceProvider.GetRequiredService<IAdmissionPolicyServices>();
                var policyResult = await admissionPolicyServices.SearchAdmissionPoliciesByEmbeddingAsync(query, topK);
                if (policyResult.Data?.Any() == true)
                {
                    moduleResults["招生政策"] = policyResult.Data;
                    contextBuilder.AppendLine("招生政策信息：");
                    foreach (var item in policyResult.Data)
                    {
                        contextBuilder.AppendLine($"政策名称：{item.AdmissionPolicyName}");
                        contextBuilder.AppendLine($"政策内容：{item.AdmissionPolicyContent}");
                    }
                }
            }

            using (var scope3 = _serviceProvider.CreateScope())
            {
                var majorInfoServices = scope3.ServiceProvider.GetRequiredService<IMajorInfoServices>();
                var majorResult = await majorInfoServices.SearchMajorInfosByEmbeddingAsync(query, topK);
                if (majorResult.Data?.Any() == true)
                {
                    moduleResults["专业信息"] = majorResult.Data;
                    contextBuilder.AppendLine("专业信息：");
                    foreach (var item in majorResult.Data)
                    {
                        contextBuilder.AppendLine($"专业名称：{item.MajorName}");
                        contextBuilder.AppendLine($"课程：{string.Join(", ", item.Courses)}");
                        contextBuilder.AppendLine($"就业前景：{item.CareerProspects}");
                    }
                }
            }

            var context = contextBuilder.ToString();
            if (string.IsNullOrEmpty(context))
            {
                context = "暂无相关信息";
            }

            // 获取AI回答
            var aiResponse = await _deepSeekService.GetChatResponseAsync(query, context, cancellationToken);

            // 记录问答历史
            var qaHistory = new QAHistoryDto
            {
                Query = query,
                Answer = aiResponse,
                QueryType = "DeepSeek问答",
                Confidence = moduleResults.Count > 0 ? "高" : "低",
                UserIP = HttpContext.Connection.RemoteIpAddress?.ToString(),
                UserAgent = HttpContext.Request.Headers["User-Agent"].ToString()
            };

            await _qaHistoryServices.CreateQAHistoryAsync(qaHistory);

            return Ok(new
            {
                Query = query,
                Answer = aiResponse,
                TotalModules = moduleResults.Count,
                Results = moduleResults,
                Timestamp = DateTime.Now,
                Source = "DeepSeek AI问答系统"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new
            {
                Query = query,
                Error = "DeepSeek AI服务暂时不可用，请稍后重试",
                Details = ex.Message,
                Source = "DeepSeek AI问答系统"
            });
        }
    }
} 